package com.sinochem.yunlian.ship.common.mq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: houshihao
 * @description: 发送im聊天消息
 * @date: 2018/3/27 11:08
 * @modified By :
 * @version:
 */
@Component
@Slf4j
public class ImMessageService {


    /**
     * @description:  指定topic发送rocketmq消息
    */
    public boolean sendImMessage(ImMessage imMessage){
        return this.sendImMessage(imMessage, producerTopic);
    }
    public boolean sendImMessage(ImMessage imMessage,String topic) {
        log.info("--sendImMessage start-- imMessage info:{}", JSON.toJSONString(imMessage));
        boolean sendSuccess = false;
        Message message = new Message(topic, JSON.toJSONBytes(imMessage));
        try {
            SendResult sendResult = defaultProducer.send(message);
            sendSuccess = sendResult != null && sendResult.getSendStatus() != null && sendResult.getSendStatus() == SendStatus.SEND_OK;
            if (sendSuccess) {
                log.info("--sendImMessage success-- msgId:{} ,imMessage info:{}", sendResult.getMsgId(), JSON.toJSONString(imMessage));
            }
        } catch (Exception e) {
            log.error("发送消息报错：{}",e.getMessage());
            log.error("--ImMessageService#sendImMessage error-- imMessage info:{}",imMessage,e);
        }
        return sendSuccess;
    }

//
    @Value("${rocketmq.chatGroup.message.topic:#{null}}")
    private String producerTopic;


    @Resource
    private DefaultMQProducer defaultProducer;
}
